/**
 * @filename:FormulaServiceImpl 2022-3-5
 * @project Wonder Java前后台分离框架  1.1.0
 * Copyright(c) 2022 Wonder Co. Ltd. 
 * All right reserved. 
 */
package com.wonder.admin.service.impl;

import com.wonder.admin.domain.Formula;
import com.wonder.admin.mapper.FormulaDao;
import com.wonder.admin.service.FormulaService;
import com.wonder.admin.request.FormulaRequest;
import com.wonder.common.utils.StringUtils;
import com.wonder.common.utils.DateUtils;
import com.wonder.common.utils.MessageUtils;
import com.wonder.common.common.AjaxMap;
import java.util.Map;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.alibaba.fastjson.serializer.AnnotationSerializer;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**   
 * @Description:TODO(编号管理服务实现)
 *
 * @version: 1.1.0
 * @author: Wonder
 * 
 */
@Service
public class FormulaServiceImpl  extends ServiceImpl<FormulaDao, Formula> implements FormulaService  {

    /**
     * 验证编号管理信息
     * 
     * @param Formula信息
     * @return 结果
     */
    @Override
    public String validate(Formula formula,String type){
    
    
       return "";
    }
    
    /**
	 * Description:编号管理分页返回
	 * @request:检索条件
	 * @page：分页参数
	 * @return:分页记录
	 */
	@Override 
	public IPage<Formula> selectList(FormulaRequest request, Page<Formula> page){
	    LambdaQueryWrapper<Formula> lambdaQueryWrapper = new LambdaQueryWrapper<>();
	    
        if (StringUtils.hasText(request.getFormula_id())) {
			    lambdaQueryWrapper.eq(Formula::getFormula_id, request.getFormula_id());
		    } 
             
        
		Page<Formula> selectPage = this.baseMapper.selectPage(page, lambdaQueryWrapper);

		return selectPage;
    }
	
	 /*Get the first part of Separator*/
	 private String GetTokenFirst(String Source, String Separator)
    {
        int p;
        String ret;
        p = Source.indexOf(Separator);
        if (p == -1)
        {
            ret = Source;          
        }///	' make the original source of zero length
        else
        {
            ret = Source.substring(0, p); /// Mid(source, 1, p - 1) ' otherwise, return just the token and   
        }
        return ret;
    }
	 
	 /*Get the first part of Separator*/
	 private String GetTokenLast(String Source, String Separator)
    {
        int p;
        String ret;
        p = Source.indexOf(Separator);
        if (p == -1)
        {
            ret = "";          
        }///	' make the original source of zero length
        else
        {
            ret = Source.substring(p + Separator.length()); ///strip it & the separator /// Mid(source, 1, p - 1) ' otherwise, return just the token and   
        }
        return ret;
    }
	/**
	 *  
	 */
	@SuppressWarnings("deprecation")
	@Transactional(isolation = Isolation.READ_COMMITTED) 
	@Override
	public String getKey(String formulaId) {
		
		 String   comb, ls_token, s, Mode1, result, ls_value;
      int i, l, n;
      String serial;
      String t1;
      Date old_date, last_date;
      Date d = new Date();
      boolean init;
      
      QueryWrapper<Formula> query=new QueryWrapper<Formula>().eq("formula_id", formulaId).last("for update");
      Formula formula=this.baseMapper.selectOne(query);//this.getById(formulaId);
      if(formula==null)
     	 return "";
      comb=formula.getTemplate(); //Template
      serial=formula.getLastvalue();//Last value
      if(StringUtils.isBlank(serial))
     	 serial="";
      old_date=formula.getLastdate();
   
      
      if(old_date==null)
     	 old_date=DateUtils.parseDate("1900/01/01");
 
      last_date =DateUtils.nowDateTime();
      


      ls_value = "";

      result = "";
      
      s="";

      comb = comb.trim();

      while (comb.length() > 0)// != "")

      {
     	 ls_token=GetTokenFirst(comb,"+").trim();
     	 comb=GetTokenLast(comb,"+").trim();
     	 
     	 s=GetTokenFirst(ls_token,"(").trim();
     	 ls_token=GetTokenLast(ls_token,"(").trim();
     	 

          switch(s.toUpperCase())

          {

              case "#NSERIAL":
             	 
             	 t1=GetTokenFirst(ls_token,",").trim();
             	 ls_token=GetTokenLast(ls_token,",").trim();
             	 n=Integer.parseInt(t1);
             	 
             	 Mode1=GetTokenFirst(ls_token,")").trim().toUpperCase();
             	 ls_token=GetTokenLast(ls_token,")").trim();
             	 
             	 s=StringUtils.repeat('0', n);
             	 init= StringUtils.isEmpty(serial);
             	 switch(Mode1)
                  {
                      case "D":
                     	 if(old_date.getDay()!=last_date.getDay()) init=true;
                     	 break;
                     	 

                      case "M":
                     	 if(old_date.getMonth()!=last_date.getMonth()) init=true;

                          break;

                      case "Y": 
                     	 if(old_date.getYear()!=last_date.getYear()) init=true;
                     	 break;

                      default:
                     	 init=false;

                          break;



                  }
             	 init=init?init:StringUtils.isEmpty(serial);
             	 if(init)
             	 {
             		 serial=StringUtils.repeat('0', n-1);
             		 serial=serial+"1";
             	 }else {
             		 l=Integer.parseInt(serial) +1;
             		 serial=String.valueOf(l);
             		 if(serial.length()<=n)
             		 {
             			 serial=StringUtils.repeat('0', n-serial.length()) +  serial;
             		 }
             		 
             	 }
             	 
             	 result=serial;
             	 break;

              case "#Y":
             	
             	 SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
             	 result=StringUtils.lastString(sdf.format(d),1);

                  break;

              case "#YY":
             	 SimpleDateFormat sdf1 = new SimpleDateFormat("yy");
             	 result=sdf1.format(d);
                  break;

              case "#YYYY":
             	 SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy");
             	 result=sdf2.format(d);
                  break;

              case "#MM":
             	 SimpleDateFormat sdf3 = new SimpleDateFormat("MM");
             	 result=sdf3.format(d);

                  break;

              case "#MMM":
             	 SimpleDateFormat sdf4 = new SimpleDateFormat("MMM");
             	 result=sdf4.format(d);

              case "#DD":
             	 SimpleDateFormat sdf5 = new SimpleDateFormat("dd");
             	 result=sdf5.format(d);

                  break;

              case "#DDD":
             	 SimpleDateFormat sdf6 = new SimpleDateFormat("ddd");
             	 result=sdf6.format(d);


                  break;


              case "#TIME":
             	 SimpleDateFormat sdf7 = new SimpleDateFormat("HHmmss");
             	 result=sdf7.format(d);

                  break;
                  
              case "#HH":
              	 SimpleDateFormat sdf8 = new SimpleDateFormat("HH");
              	 result=sdf8.format(d);

                   break; 
             case "#HHmm":
               	 SimpleDateFormat sdf9 = new SimpleDateFormat("HHmm");
               	 result=sdf9.format(d);

                    break;          

              case "#UNIQUEINT":
             	 
             	 i=Integer.parseInt(serial)+1;
             	 result=String.valueOf(i);

                  break;

              default:

                  result =s.trim();

                  break;

          }

          ls_value = ls_value + result;

      }

      if (ls_value.length() > 0 && result.length() > 0)

      {
     	 formula.setLastvalue(result);
     	 formula.setLastdate(last_date);
     	 if(this.updateById(formula)) //Update it
             return ls_value;
     	 else
     		 return "";

      }

      else

      {
     	 return "";

      }

  }
        
    
	
}